﻿using System;
using System.Collections.Generic;
using System.Linq;
using Abp.AutoMapper;
using Abp.Runtime.Session;
using Hicap.AuthorizationServer.Core.Models;

namespace Hicap.AuthorizationServer.Core.Managers.Authorization
{
    public class PermissionCheckerManager : AuthorizationServerDomainServiceBase, IPermissionCheckerManager
    {
        private readonly IAbpSession _abpSession;
        private readonly IUserManager _userManager;
        private readonly IUserRoleRelatedManager _userRoleRelatedManager;
        private readonly IAuthObjectRoleRelatedManager _authObjectRoleRelatedManager;

        public PermissionCheckerManager(
            IUserManager userManager,
            IUserRoleRelatedManager userRoleRelatedManager,
            IAuthObjectRoleRelatedManager authObjectRoleRelatedManager,
            IAbpSession abpSession)
        {
            _userManager = userManager;
            _userRoleRelatedManager = userRoleRelatedManager;
            _authObjectRoleRelatedManager = authObjectRoleRelatedManager;
            _abpSession = abpSession;
        }

        public bool CheckPermission(string authObject)
        {
            var userId = Convert.ToInt32(_abpSession.UserId.Value);
            var userAuth = GetFromDatabase(userId);
            return userAuth.AuthObjects.Select(x => x.ObjectCode).Contains(authObject);
        }

        private UserAuth GetFromDatabase(int id)
        {
            var result = new UserAuth();
            //... 从数据库中检索数据
            var roles = _userRoleRelatedManager.GetRole(id);

            var auths = _authObjectRoleRelatedManager.GetAuthRole(roles);

            result.Roles = roles.MapTo<List<Role>>();
            result.AuthObjects = auths.MapTo<List<AuthObject>>();
            result.User = _userManager.GetUserById(id);

            return result;
        }
    }
}